package com.ky.manage.utils;

import android.text.TextUtils;

import com.ky.manage.BaseApplication;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by dell on 2018/7/6.
 */

public class StringUtil {

    /**
     * 转化公里标为STRING类型
     *
     * @return
     */
    public static String strMileage = "";
    //把spiner里面String转化成毫秒
    static String[] arr = {"10分钟", "20分钟", "30分钟", "40分钟", "50分钟", "60分钟", "70分钟", "80分钟", "90分钟", "100分钟", "110分钟", "120分钟"};
    private static ThreadLocal<SimpleDateFormat> DateLocal = new ThreadLocal<>();
    private static String REGEX_CHINESE = "[\u4e00-\u9fa5]";// 中文正则
    private static StringBuffer mTtsSb = new StringBuffer();

    /**
     * 获取资源字符串
     *
     * @param resId
     * @return
     */
    public static String getResString(int resId) {
        return BaseApplication.getContext().getResources().getString(resId);
    }

    // strTime要转换的String类型的时间
    // formatType时间格式
    // strTime的时间格式和formatType的时间格式必须相同
    public static long stringToLong(String strTime, String formatType) {
        if (TextUtils.isEmpty(strTime)) {
            return 0;
        }
        Date date = stringToDate(strTime, formatType); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = dateToLong(date); // date类型转成long类型
            return currentTime;
        }
    }

    public static int stringToInt(String strTime) {
        if (TextUtils.isEmpty(strTime)) {
            return 0;
        }
        Date date = stringToDate(strTime, "yyyy-MM-dd HH:mm:ss"); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = dateToLong(date); // date类型转成long类型
            return (int) (currentTime / 1000);
        }
    }

    //不带横杠的时间转成带横杠的时间  yyyy-MM-dd HH:mm
    public static String getYmd(String strTime) {
        strTime = strTime.substring(0, 4) + "-" + strTime.substring(4, 6) + "-" + strTime.substring(6, 8) + " " + strTime.substring(8, 10) + ":" + strTime.substring(10, 12);
        return strTime;
    }

    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        try {
            date = formatter.parse(strTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    // date要转换的date类型的时间
    public static long dateToLong(Date date) {
        return date.getTime();
    }

    public static int timeInt(String str) {
        if (arr[0].equals(str)) {
            return 60 * 10;
        } else if (arr[1].equals(str)) {
            return 60 * 20;
        } else if (arr[2].equals(str)) {
            return 60 * 30;
        } else if (arr[3].equals(str)) {
            return 60 * 40;
        } else if (arr[4].equals(str)) {
            return 60000 * 50;
        } else if (arr[5].equals(str)) {
            return 60 * 60;
        } else if (arr[6].equals(str)) {
            return 60 * 70;
        } else if (arr[7].equals(str)) {
            return 60000 * 80;
        } else if (arr[8].equals(str)) {
            return 60 * 90;
        } else if (arr[9].equals(str)) {
            return 60 * 100;
        } else if (arr[10].equals(str)) {
            return 60 * 110;
        } else if (arr[11].equals(str)) {
            return 60 * 120;
        }
        return 1000000;
    }

    //int类型转成String类型年月日
    public static String getTimeStringToInt(long time) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(time);
    }

    public static String getLongTimeToString(long time) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(time);
    }

    public static String getLongTimeToString2(long time) {
        return new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(time);
    }

    //年月日
    public static String getYmdDate(int time) {
        return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(time * 1000L);
    }

    //时分
    public static String getNoYmdTime(long time) {
        return new SimpleDateFormat("HH:mm", Locale.getDefault()).format(time * 1000L);
    }

    //时分
    public static String getNoYmdSSTime(long time) {
        return new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(time);
    }

    //时分秒
    public static String getHMS(long time) {
        String h = "00";
        String m = "00";
        String s = "00";
        if (time / (1000 * 60 * 60) > 0) {
            h = time / (1000 * 60 * 60) >= 10 ? time / (1000 * 60 * 60) + "" : "0" + time / (1000 * 60 * 60);
            if (time % (1000 * 60 * 60) >= (1000 * 60)) {
                m = time % (1000 * 60 * 60) / (1000 * 60) >= 10 ? time % (1000 * 60 * 60) / (1000 * 60) + "" : "0" + time % (1000 * 60 * 60) / (1000 * 60);
                if (time % (1000 * 60 * 60) % (1000 * 60) >= 1000) {
                    s = time % (1000 * 60 * 60) % (1000 * 60) / 1000 >= 10 ? time % (1000 * 60 * 60) % (1000 * 60) / 1000 + "" : "0" + time % (1000 * 60 * 60) % (1000 * 60) / 1000;
                }
            } else if (time % (1000 * 60 * 60) / 1000 > 0) {
                s = time % (1000 * 60 * 60) / 1000 >= 10 ? time % (1000 * 60 * 60) / 1000 + "" : "0" + time % (1000 * 60 * 60) / 1000;
            }

        } else if (time / (1000 * 60) > 0) {
            m = time / (1000 * 60) >= 10 ? "" + time / (1000 * 60) : "0" + time / (1000 * 60);
            if (time % (1000 * 60) > 1000) {
                s = time % (1000 * 60) / 1000 >= 10 ? "" + time % (1000 * 60) / 1000 : "0" + time % (1000 * 60) / 1000;
            }
        } else if (time / 1000 > 0) {
            s = time / 1000 >= 10 ? "" + time / 1000 : "0" + time / 1000;
        }
        return h + ":" + m + ":" + s;
    }

    //int类型转成String类型年月日
    public static String getTimeStringToInt2(long time) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(time);
    }

    //当前时间转成无杠日期
    public static String getYmdTime(long time) {
        return new SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(time);
    }

    //获得当天0点时间
    public static int getTimesmorning() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (int) (cal.getTimeInMillis() / 1000);
    }

    //获得当天24点时间
    public static int getTimesnight() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 24);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (int) (cal.getTimeInMillis() / 1000);
    }

    /**
     * 获取一个月前的日期
     *
     * @param date 传入的日期
     * @return
     */
    public static String getMonthAgo(Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        String monthAgo = simpleDateFormat.format(calendar.getTime());
        return monthAgo;
    }

    /**
     * 转换字符串（GBK）
     *
     * @param bytes 字节数组
     * @return
     */
    public static String hexStr2Str(byte[] bytes) {
        String result = "";
        try {
            //转中文
            result = new String(bytes, "GBK");
            //去除回车换行
            result = result.replace("\r\n", " ");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            result = "";
        } catch (Exception e) {
            e.printStackTrace();
            result = "";
        }
        boolean gbkDecodeSuccess = Charset.forName("GBK").newEncoder().canEncode(result);
        if (!gbkDecodeSuccess) {
            result = "";
        }
        return result;
    }

    /**
     * 判断是否为今天(效率比较高)
     *
     * @param day 传入的 时间  "2016-06-28 10:10:30" "2016-06-28" 都可以
     * @return true今天 false不是
     * @throws ParseException
     */
    public static boolean isToday(String day) {

        Calendar pre = Calendar.getInstance();
        Date predate = new Date(System.currentTimeMillis());
        pre.setTime(predate);
        Calendar cal = Calendar.getInstance();
        Date date = null;
        try {
            date = getDateFormat().parse(day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        cal.setTime(date);
        if (cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR))) {
            int diffDay = cal.get(Calendar.DAY_OF_YEAR)
                    - pre.get(Calendar.DAY_OF_YEAR);

            return diffDay == 0;
        }
        return false;
    }

    public static SimpleDateFormat getDateFormat() {
        if (null == DateLocal.get()) {
            DateLocal.set(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA));
        }
        return DateLocal.get();
    }

    /**
     * 判断在不在当天晚上 2点到2点01
     * true 是范围内，false 范围外
     */
    public static boolean isScope() {
        Calendar cal = Calendar.getInstance();// 当前日期
        int hour = cal.get(Calendar.HOUR_OF_DAY);// 获取小时
        int minute = cal.get(Calendar.MINUTE);// 获取分钟
        int minuteOfDay = hour * 60 + minute;// 从0:00分开是到目前为止的分钟数
        final int start = 2 * 60 + 1;// 起始时间 00:20的分钟数
        final int end = 2 * 60 + 2;// 结束时间 8:00的分钟数
        return minuteOfDay >= start && minuteOfDay <= end;
    }

    public static String isEmpty(String txt) {
        if (TextUtils.isEmpty(txt) || txt.equals("null")) {
            txt = "";
        }
        return txt;
    }

    /**
     * 去掉中文
     */
    public static String testStr(String str) {
        // 去除中文
        Pattern pat = Pattern.compile(REGEX_CHINESE);
        Matcher mat = pat.matcher(str);
        return mat.replaceAll("");
    }

    /**
     * 无中文字符串
     *
     * @param text
     * @return
     */
    public static String DontChinese(String text) {
        if (isChinese(text)) { //如果有中文
            if (text.contains("/")) {
                return text.substring(0, text.lastIndexOf("/"));
            } else {
                return testStr(text);
            }
        } else {
            return text;
        }
    }

    /**
     * 转化atp类型
     *
     * @param
     * @return
     */
    public static String atpString(String atp) {
        String[] trainSizes = new String[]{"200H", "200C", "300D", "300S", "300T", "300H", "200T", "200K", "300TATO", "300SATO", "200CATO"};
        Map<String, String> trainSizeMap = new HashMap<>();
        for (int i = 1; i < 12; i++) {    //匹配ATP类型
            trainSizeMap.put("" + i, trainSizes[i - 1]);
        }
        return trainSizeMap.get(atp);
    }

    /**
     * 字符串之间添加功空格
     *
     * @param text
     * @return
     */
    public static String getNewText(String text) {
        String newText = "";
        for (int i = 0; i < text.length(); i++) {
            newText += (text.substring(i, i + 1) + " ");
        }
        return newText;
    }

    /**
     * 字符串转换成十六进制字符串
     *
     * @param str 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;

        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * bytes转换成十六进制字符串
     *
     * @param b byte数组
     * @return String 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }

    public static String getStrMileage(int mileage) {

        if (mileage % 1000 >= 100) {
            strMileage = "K" + mileage / 1000 + "+" + mileage % 1000;
        } else if (mileage % 1000 >= 10) {
            strMileage = "K" + mileage / 1000 + "+0" + mileage % 1000;
        } else {
            strMileage = "K" + mileage / 1000 + "+00" + mileage % 1000;
        }
        return strMileage;
    }

    // 判断一个字符是否是中文
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }

    // 判断一个字符串是否含有中文
    public static boolean isChinese(String str) {
        if (str == null)
            return false;
        for (char c : str.toCharArray()) {
            if (isChinese(c))
                return true;// 有一个中文字符就返回
        }
        return false;
    }

    //返回A-Z
    public static String getAZ(int i) {
        Map<Integer, String> mapAZ = new HashMap<>();
        String[] az = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
                "S", "T", "U", "V", "W", "X", "Y", "Z"};
        for (int j = 0; j < az.length; j++) {
            mapAZ.put(j, az[j]);
        }
        return mapAZ.get(i);
    }

    //返回A-Z
    public static String getAZ(String text) {
        if (!TextUtils.isEmpty(text) && text.split(",").length > 0) {
            Map<Integer, String> mapAZ = new HashMap<>();
            String[] az = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
                    "S", "T", "U", "V", "W", "X", "Y", "Z"};
            for (int j = 0; j < az.length; j++) {
                mapAZ.put(j, az[j]);
            }
            String newText = "";
            for (int i = 0; i < text.split(",").length; i++) {
                if (text.split(",")[i].equals("1")) {
                    newText += ("," + mapAZ.get(i));
                } else if (!text.split(",")[i].equals("0")) {
                    newText += ("," + text.split(",")[i]);
                }
            }
            if (TextUtils.isEmpty(newText)) {
                return "";
            } else {
                return newText.substring(1, newText.length());
            }
        } else {
            return text;
        }
    }


    /**
     * 获取数字值
     *
     * @param value
     * @return
     */
    public static String getNumberValue(String value) {
        if (TextUtils.isEmpty(value)) {
            return "";
        }
        String realValue = "0";
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(value);
        realValue = m.replaceAll("").trim();
        return realValue;
    }

    /**
     * 获取字符串中的数字
     */
    public static String getInt(String mileAge) {
        String valueReal = "0";
        if (!TextUtils.isEmpty(mileAge)) {
            int[] mileList = new int[4];
            String value = "";
            int k = 0;
            boolean isDigit = false;
            for (int j = 0; j < mileAge.length(); j++) {
                if (Character.isDigit(mileAge.charAt(j))) {
                    isDigit = true;
                    value += mileAge.charAt(j);
                } else {
                    if (isDigit) {
                        mileList[k++] = Integer.valueOf(value);
                    }
                    if (k == 2)
                        break;
                    isDigit = false;
                    value = "";
                }
            }

            if (isDigit && k < 2) {
                mileList[k++] = Integer.valueOf(value);
            }
            if (k == 2) {
                valueReal = String.valueOf(mileList[0] * 1000 + mileList[1]);
            } else {
                valueReal = String.valueOf(mileList[0] * 1000);
            }
        }
        return valueReal;
    }
}
